function ListNode(val, next) {
  this.val = (val===undefined ? 0 : val)
  this.next = (next===undefined ? null : next)
}
function createList(arr) {
  if(arr.length == 0)
    return null;
  let head = new ListNode(arr[0], null), headNode = head;
  for(let i = 1; i < arr.length; i++) {
    let temp = new ListNode(arr[i], null);
    head.next = temp;
    head = temp;
  }
  return headNode;
}
function showList(head) {
  while(head) {
    console.log(head.val);
    head = head.next;
  }
}
/**
 * @param {ListNode} head
 * @return {boolean}
*/
var isPalindrome = function(head) {
  // 反转链表
  function reverseList(head) {
    if(head == null)
      return head;
    let newHeader = new ListNode(head.val, null);
    head = head.next;
    while(head) {
      let tempNode = head.next
      head.next = newHeader;
      newHeader = head;
      head = tempNode;
    }
    return newHeader;
  };
  let count = 0, newHeader = head, temp = head;
  while(temp) {
    count++;
    temp = temp.next;
  }
  count = Math.floor(count / 2);
  temp = head;
  while(temp) {
    temp = temp.next;
    if(count == 0) {
      newHeader = newHeader.next;
    } else {
      count--;
    }
  }
  newHeader = reverseList(newHeader);
  while(head && newHeader) {
    if(head.val != newHeader.val)
      return false;
    head = head.next;
    newHeader = newHeader.next;
  }
  return true;
};
let head = [1,2,2,1];
head = createList(head);
console.log(isPalindrome(head));
head = [1,2];
head = createList(head);
console.log(isPalindrome(head));
head = [1,2,2,2,1];
head = createList(head);
console.log(isPalindrome(head));
